<template>
  <!-- 发布宝贝详情 -->
  <div class="app-container">
    <!-- 分类信息 -->
    <el-form ref="form" :model="form" label-width="100px" class="demo-ruleForm" size="small">
      <el-card class="box-card">
        <div class="form-container">
          <el-form-item label="当前分类：">
            {{ classifyName }}
            <el-button type="primary" style="margin-left: 20px;" @click="changingOverClassify">切换分类</el-button>
          </el-form-item>
        </div>
      </el-card>
      <!-- 基础信息 -->
      <firstForm v-if="classify_id.length > 0" ref="firstForm" :form="form" :classify_id="classify_id" :supplier="supplier" @msgEvent="sendFirstMsg"/>
      <!-- 销售信息 -->
      <secondForm
        ref="secondForm"
        :form="form"
        :specifications="specifications"
        :percent="percent"
        :consume-prop="consume"
        :generalize-prop="generalize"
        @msgEvent="sendSecondMsg"/>
      <!-- 图文描述 -->
      <thirdForm ref="thirdForm" :form="form" @msgEvent="sendThirdMsg"/>
      <!-- 富文本编辑器 -->
      <editor ref="editor" :form="form" @saveContent="saveContent"/>
      <!--物流信息,运费-->
      <!--<logistics
        ref="logistics"
        :form="form"
        :freight="freight"
        @msgEvent="sendLogisticsMsg"
        @getFreightList="getFreightList"/>-->
      <!--会员等级信息-->
      <member-grade ref="memberGrade" :member-config="memberConfig" :form="form" @msgEvent="saveGrade"/>
      <!-- 其他信息 -->
      <other ref="otherForm" :form="form" @other="sendOther"/>
    </el-form>
    <div class="fixed-bottom">
      <el-button :loading="addLoading" size="small" @click="cancel">取消</el-button>
      <el-button :loading="addLoading" size="small" type="primary" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script>
import firstForm from './firstForm'
import secondForm from './secondForm'
import thirdForm from './thirdForm'
import editor from './editor'
import logistics from './logistics'
import memberGrade from './memberGrade'
import other from './other'
import Cookies from 'js-cookie'
import {
  getVariety,
  getCommodityById,
  getSupplierList,
  getSpecificationsList,
  // getFreightList,
  getShopConfig,
  getMemberConfig
} from '@/api/mall/commodity'
import { addCommodity } from '@/api/mall/commodityForAdd'
import Vue from 'vue'

export default {
  components: { firstForm, secondForm, thirdForm, editor, logistics, memberGrade, other },
  mixins: [],
  data() {
    return {
      form: {},
      classify_id: [], // 分类id
      commodity_id: '', // 商品id
      classifyName: '', // 分类名
      firstClassName: '', // 一级分类名
      parameter: [], // 宝贝参数
      specifications: [], // 宝贝规格
      // freight: [], // 运费模版
      supplier: [], // 供应商列表
      firstResult: false, // 组件返回状态
      secondResult: false, // 组件返回状态
      thirdResult: false, // 组件返回状态
      logisticsResult: false, // 组件返回状态
      addLoading: false, // 提交表单
      otherResult: false, // 其他信息组件返回状态
      percent: 0, // 佣金总额比例 20% 为 20.0
      consume: 0, // 消费收益比例
      generalize: 0, // 推广收益比例
      memberConfig: {}, // 获取会员设置，grade_list为等级信息
      state: 0 // 状态码，1：从当前页面跳转至选择分类页面在进入此页面 0：默认状态，从发布宝贝的选择分类页面，宝贝列表页面编辑功能进入
    }
  },
  created() {
    // 从商品分类、商品列表传递过来的分类id，（必填项）
    const classify_id = this.$route.query.classify_id
    if (classify_id && classify_id.length > 0) {
      this.classify_id = classify_id.split(',')
    }
    // 状态码：为1时从cookie中取商品信息
    const state = this.$route.query.state
    if (state && Number(state)) {
      this.state = Number(state)
    }
    //  从商品分类、商品列表传递过来的商品id （选填项，没有值则代表新增商品，有值代表了编辑原有商品）
    const commodity_id = this.$route.query.commodity_id
    if (commodity_id && commodity_id.length > 0) {
      this.commodity_id = commodity_id
    }
    // 获取运费模版
    // this.getFreightList()
    // 获取供应商列表
    this.getSupplier()
    // 获取规格，规格是数据字典，协助快速填写商品的规格以及参数
    this.getSpecifications()
    // 获取当前分类信息，主要用于页面渲染分类信息
    this.getClassify()
    // 获取当前商品信息
    this.getCommodityInfo()
    // 获取商城配置
    this.getShopConfig()
    // 获取会员设置信息，包含等级信息
    this.getMemberGrade()
  },
  methods: {
    getSpecifications() {
      // 获取规格，规格是数据字典，协助快速填写商品的规格以及参数
      getSpecificationsList().then(res => { this.specifications = res })
    },
    getCommodityInfo() {
      // 当所选分类不合适，切换分类后再次进入该页面时，先从全局中获取先前保存的商品信息，不用再去后台请求数据
      const info = this.$commodityInfo
      if (info && this.state > 0) {
        this.$nextTick(() => {
          this.form = info
          // 分类id回填商品,为取分类参数做准备
          this.form.classify_id = this.classify_id
          Vue.prototype.$commodityInfo = ''
        })
        return
      }
      // 网络请求，根据商品id获取商品信息回显
      if (this.commodity_id && this.commodity_id.length > 0) {
        // 获取当前商品信息
        getCommodityById({ 'commodity_id': this.commodity_id }).then(res => {
          this.parameter = res.parameter
          this.form = res
          // 分类id回填商品,为取分类参数做准备
          this.form.classify_id = this.classify_id
        })
      } else {
        // 属于新增商品信息，其他字段皆为空，需要绑定分类id
        this.form.classify_id = this.classify_id
      }
    },
    getClassify() {
      // 获取当前分类信息，分类回显
      getVariety({ 'variety_id': this.classify_id[0] }).then(res => {
        // 一级分类
        if (res.variety_id === this.classify_id[0]) {
          this.classifyName = res.variety_name
          this.firstClassName = res.variety_name
          // 选择的有二级分类
          if (this.classify_id.length > 1) {
            res.secondVarietyList.map(info => {
              if (info.second_variety_id === this.classify_id[1]) {
                this.classifyName += ' >> ' + info.second_variety_name
              }
            })
          }
        }
      })
    },
    // getFreightList() {
    //   // 获取运费列表
    //   getFreightList().then(res => {
    //     this.freight = res
    //   })
    // },
    getShopConfig() {
      // 获取商城配置信息
      getShopConfig().then(res => {
        // 佣金总额比例 20% 为 20.0
        this.percent = res.commission_percent
        // 消费收益比例
        this.consume = res.consume_percent
        // 推广收益比例
        this.generalize = res.generalize_percent
      })
    },
    getSupplier() {
      // 获取供应商
      getSupplierList().then(res => {
        this.supplier = res
      })
    },
    getMemberGrade() {
      // 获取会员设置，包含会员等级
      getMemberConfig().then(res => {
        this.memberConfig = res.result
      })
    },
    changingOverClassify() {
      // 切换分类，切换宝贝当前分类页面跳转
      // 被动调用子组建获取传值方法，获取已经修改的内容
      this.getUpdateForm()
      // 商品信息，全局挂载,当分类从新选择之后，再次进入此页面从全局获取当前编辑的信息
      Vue.prototype.$commodityInfo = Object.assign({}, (this.form))
      // 数组转字串便于页面解析
      const query = { 'classify_id': this.classify_id.join(','), 'commodity_id': this.commodity_id, 'state': 1, 'checkType': '2' }
      this.$router.push({ path: '/commodity/classify', query: query })
    },
    getUpdateForm() {
      // 被动调用子组建获取传值方法，已经修改的内容
      this.$refs.firstForm.sendFirstMsg()
      this.$refs.secondForm.sendSecondMsg()
      this.$refs.thirdForm.sendThirdMsg()
      this.$refs.editor.saveContent()
      // this.$refs.logistics.sendLogisticsMsg()
      this.$refs.memberGrade.saveMsg()
      this.$refs.otherForm.sendOther()
    },
    submitForm() {
      // 被动调用子组建获取传值方法，获取已经修改的内容
      this.getUpdateForm()
      this.otherResult = !this.$refs.otherForm.errorList.length
      // 校验不通过，驳回
      if (!this.firstResult || !this.secondResult || !this.thirdResult || !this.otherResult) {
        this.$message({
          message: '请完善内容',
          type: 'warning'
        })
        return false
      }
      console.log(this.form, '999999')
      this.addLoading = true
      // 主要字段，商品id，分类id，分类名
      this.form.commodity_id = this.commodity_id
      this.form.variety_id = this.classify_id[0]
      this.form.variety_name = this.firstClassName
      this.form.second_variety_id = this.classify_id.length > 1 ? this.classify_id[1] : ''
      // 添加宝贝,提交请求后台
      addCommodity(this.form).then(res => {
        this.addLoading = false
        if (res) {
          Cookies.set('template_id', this.form.template_id)
          this.$notify({
            title: this.commodity_id ? '修改成功' : '添加成功',
            type: 'success',
            duration: 2500
          })
          this.$router.push({ path: '/commodity/success' })
        } else {
          this.$message({
            message: '商品名不允许重复',
            type: 'warning'
          })
        }
      }).catch(() => {
        this.addLoading = false
      })
    },
    // 接收第一个子组建传递过来的值
    sendFirstMsg(value) {
      // 编辑是否通过，状态值
      this.firstResult = value.result
      this.form.name = value.name
      this.form.pro_title = value.pro_title
      // 宝贝标签
      this.form.label_brand_ids = value.label_brand_ids
      // 宝贝参数
      if (value.parameter) {
        this.form.parameter = value.parameter
      }
      // 供应商信息补充
      if (value.supplier_id) {
        this.form.supplier_id = value.supplier_id
        this.supplier.map(item => {
          if (value.supplier_id === item.supplier_id) {
            this.form.supplier_name = item.supplier_name
            this.form.supplier_userid = item.user_id
          }
        })
      }
    },
    // 接收第二个子组建传递过来的值
    sendSecondMsg(value) {
      // 编辑是否通过，状态值
      this.secondResult = value.result
      this.form.vip_price = value.vip_price
      this.form.cost_price = value.cost_price
      this.form.price = value.price
      this.form.share_save = value.share_save
      this.form.commission = value.commission
      this.form.inventory = value.inventory
      this.form.union_code = value.union_code
      this.form.specifications = value.specifications
      this.form.specification_details = value.specification_details
    },
    // 接收第三个子组建传递过来的值
    sendThirdMsg(value) {
      // 编辑是否通过，状态值
      this.thirdResult = value.result
      this.form.link_url = value.link_url
      this.form.cover_url = value.cover_url
      this.form.vedio_url = value.vedio_url
    },
    saveContent(value) {
      // 富文本编辑器内容保存
      this.form.detail = value
    },
    // sendLogisticsMsg(value) {CardCommodityEntity
    //   // 接收物流信息，选择运费模板
    //   // 编辑是否通过，状态值
    //   this.logisticsResult = value.result
    //   this.form.template_id = value.template_id
    // },
    sendOther(value) {
      this.form.state = value.state
      this.form.listing_time = value.listing_time
      this.form.advance_sale_check = value.advance_sale_check
      this.form.advance_sale_state = value.advance_sale_state
      this.form.advance_sale_time = value.advance_sale_time
      this.form.advance_sale_day = value.advance_sale_day
      this.form.home_purchase_restrictions_check = value.home_purchase_restrictions_check
      this.form.home_purchase_restrictions_state = value.home_purchase_restrictions_state
      this.form.home_purchase_restrictions_count = value.home_purchase_restrictions_count
      this.form.start_selling_count = value.start_selling_count
    },
    saveGrade(value) {
      // 获取等级传值
      this.form.grade_id_list = value
    },
    cancel() {
      const commodity_id = this.$route.query.commodity_id
      if (commodity_id && commodity_id.length > 0) {
        this.$router.push({ path: '/commodity/list' })
      } else {
        const query = { 'classify_id': this.classify_id.join(','), 'commodity_id': this.commodity_id }
        this.$router.push({ path: '/commodity/classify', query: query })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    padding-bottom: 50px;
  }

  .form-container {
    width: 90%;
  }

  .box-card {
    margin-bottom: 10px;
  }

  .el-card__body {
    padding: 20px 20px 0 20px !important;
  }

  .fixed-bottom {
    position: absolute;
    bottom: 0;
    z-index: 10099;
    background: hsla(0, 0%, 100%, .95);
    padding: 10px;
    border-top: none;
    width: calc(100% - 20px);
    box-shadow: 0 -3px 5px #eee;
    text-align: center;
    background: #fff;
    left: 50%;
    transform: translateX(-50%);
  }
</style>
